package com.sgolub.commanndsonline.ws.entity;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.sgolub.commanndsonline.helpers.DateConverterHelper;


public class DomParserPeriod {
	
	public static List<Period> getPeriodsFromXMLString(String xmlString){
		List<Period> resultList = new ArrayList<Period>(); 
    try
    {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        
        Document document = documentBuilder.parse(new InputSource(new StringReader(xmlString)));
        //Document doc = builder.parse(new InputSource(new StringReader(soft)));
        
        document.getDocumentElement().normalize();

        System.out.println("Корневой элемент: " + document.getDocumentElement().getNodeName());
        NodeList nodeList = document.getElementsByTagName(document.getDocumentElement().getChildNodes().item(1).getNodeName());
        System.out.println("---------NodeList-----------");
        System.out.println(nodeList);
        System.out.println(nodeList.getLength());
        System.out.println("--------------------");
        
        for(int tmp = 0; tmp < nodeList.getLength(); tmp++)
        {
        	NamedNodeMap nnm = nodeList.item(tmp).getAttributes();
        	
        	Period item = new Period();
        	item.setAdvertisingArea(nnm.getNamedItem("AdvertisingArea").getNodeValue());
        	
        	String tmpBegDate = nnm.getNamedItem("StartDate").getNodeValue();
        	if (tmpBegDate.length()>0)	
        		item.setStartDate(DateConverterHelper.convertToDateWS(tmpBegDate));

        	String tmpEndDate = nnm.getNamedItem("EndDate").getNodeValue();
        	if (tmpEndDate.length()>0)	
        		item.setEndDate(DateConverterHelper.convertToDateWS(tmpEndDate));        	
        	
        	item.setStatus(nnm.getNamedItem("Status").getNodeValue());
        	
        	resultList.add(item);
        	
//			System.out.println("---------NamedNodeMap-----------");
//			System.out.println("AdvertisingArea: " + nnm.getNamedItem("AdvertisingArea").getNodeValue());
//			System.out.println("StartDate: " + nnm.getNamedItem("StartDate").getNodeValue());
//			System.out.println("EndDate: " + nnm.getNamedItem("EndDate").getNodeValue());
//			System.out.println("Status: " + nnm.getNamedItem("Status").getNodeValue());
//			System.out.println("--------------------");
        }
    }
    catch (Exception e)
    {
        System.out.println(e.getLocalizedMessage());
        e.printStackTrace();
    }
	return resultList;
	
	}	
	
	
}
